-- string iterator
-- usage:
-- for word in string.split(',', "hello, world") do print(word) end
function string.split(char,line)
   local pos = 1           -- current position in the line
   return function ()      -- iterator function
	     local s, e = string.find(line, "%w+"..char, pos)
	     if s then           -- found a word?
		   pos = e + 1       -- next position is after this word
		return string.sub(line, s, e-1)     -- return the word
	     else
		if pos > 0 then
		   local p = pos
		   pos = -1
		      return string.sub(line, p)
		   else
		      return nil
		   end
		end
		return nil            -- no more lines: end of traversal
	     end
end

-- more robust splitter
function luacalc.split(str, pat)
   local t = {n = 0}
   local fpat = "(.-)"..pat
   local last_end = 1
   local s,e,cap = string.find(str, fpat, 1)
   while s ~= nil do
      if s~=1 or cap~="" then
	 table.insert(t,cap)
      end
      last_end = e+1
      s,e,cap = string.find(str, fpat, last_end)
   end
   if last_end<=string.len(str) then
      cap = string.sub(str,last_end)
      table.insert(t,cap)
   end
   return t
end
-- character iterator
function string.foreach(str, func, index)
   index = index or 1
   func(index, string.sub(str,index, index))
   if index < string.len(str) then
      string.foreach(str, func, index+1)
   end
end

-- trim whitespace off left and right
function string.trim (s)
	s = string.gsub(s, "^%s*(.-)%s*$", "%1")
	return s
end

